class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        # 处理符号
        sign = '-' if numerator * denominator < 0 else ''
        numerator = abs(numerator)
        denominator = abs(denominator)

        # 计算整数部分
        q, r = divmod(numerator, denominator)
        if r == 0:
            return sign + str(q) if q != 0 or sign == '' else '0'

        # 初始化结果
        ans = [sign + str(q) + '.']
        r_to_pos = {}  # 记录余数出现的位置
        decimal_part = []  # 存储小数部分

        pos = 0
        while r != 0:
            # 如果余数重复出现，说明检测到循环节
            if r in r_to_pos:
                # 在循环开始位置插入括号
                non_repeating = ''.join(decimal_part[:r_to_pos[r]])
                repeating = ''.join(decimal_part[r_to_pos[r]:])
                return sign + str(q) + '.' + non_repeating + '(' + repeating + ')'

            # 记录当前余数的位置
            r_to_pos[r] = pos
            pos += 1

            # 计算下一位小数
            r *= 10
            digit, r = divmod(r, denominator)
            decimal_part.append(str(digit))

        # 如果没有循环节，直接返回结果
        return sign + str(q) + '.' + ''.join(decimal_part)


# 测试代码
def test():
    solution = Solution()

    # 测试用例
    test_cases = [
        (1, 2),  # 0.5
        (2, 1),  # 2
        (4, 333),  # 0.(012)
        (1, 3),  # 0.(3)
        (1, 6),  # 0.1(6)
        (1, 7),  # 0.(142857)
        (-1, 2),  # -0.5
        (0, 3),  # 0
        (1, 333),  # 0.(003)
    ]

    for numerator, denominator in test_cases:
        result = solution.fractionToDecimal(numerator, denominator)
        print(f"{numerator}/{denominator} = {result}")


if __name__ == "__main__":
    test()